package org.team4.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.xwork.time.DateFormatUtils;

import org.team4.util.HtmlHelper;
import org.team4.util.SmtpHelper;

/**
 * <p>
 * 程序名称： ErrorMailHelper.java
 * </p>
 * <p>
 * 程序说明： 用于发送500异常的错误邮件通知
 * </p>
 * <p>
 * 版权信息： Copyright 深圳市维远泰克科技有限公司
 * </p>
 * <p>
 * 时间： Nov 25, 2010 10:07:16 AM
 * </p>
 * 
 * @author： Marker
 * @version： Ver 0.1
 */
public class ErrorMailHelper {

	/**
	 * 发送异常邮件
	 * @param request
	 */
	public static void sendErrorMail(HttpServletRequest request) {
		boolean isLocal = request != null ? "127.0.0.1".equals(request.getRemoteAddr()) : false;
		if (!isLocal) {
			try {
				SmtpHelper sh = new SmtpHelper("www.vwintech.com");
				sh.setNamePass("用户名", "密码");
				sh.setSubject(getException(request).getClass().getSimpleName());
				sh.setBody(getErrorHtml(request, getException(request)));
				sh.setNeedAuth(false);
				sh.setTo("");
				sh.setFrom("");
				if (sh.testConnect()) {
					sh.sendout();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 将当前上下文发生的异常转为字符串
	 * @param request
	 * @return
	 */
	private static Throwable getException(HttpServletRequest request) {
		if (request == null) {
			return null;
		} else {
			Throwable t = (Throwable) request.getAttribute("javax.servlet.jsp.jspException");
			if (t == null) {
				// Tomcat错误处理方法
				t = (Throwable) request.getAttribute("javax.servlet.error.exception");
			}
			return t;
		}
	}

	/**
	 * 格式化错误信息
	 * @param request
	 * @param t
	 * @return
	 */
	private static String getErrorHtml(HttpServletRequest request, Throwable t) {
		StringBuffer html = new StringBuffer();
		if (request != null) {
			html.append("<h2>Request Headers</h2><table>");
			html.append("<tr><th>Request URL</th><td>");
			html.append(request.getRequestURL().toString());
			if (request.getQueryString() != null) {
				html.append('?');
				html.append(request.getQueryString());
			}
			html.append("</td></tr>");
			html.append("<tr><th>Remote Addr</th><td>");
			html.append(request.getRemoteAddr());
			html.append("</td></tr>");
			html.append("<tr><th>Request Method</th><td>");
			html.append(request.getMethod());
			html.append("</td></tr>");
			html.append("<tr><th>CharacterEncoding</th><td>");
			html.append(request.getCharacterEncoding());
			html.append("</td></tr>");
			html.append("<tr><th>Request Locale</th><td>");
			html.append(request.getLocale());
			html.append("</td></tr>");
			html.append("<tr><th>Content Type</th><td>");
			html.append(request.getContentType());
			html.append("</td></tr>");
			Enumeration headers = request.getHeaderNames();
			while (headers.hasMoreElements()) {
				String key = (String) headers.nextElement();
				html.append("<tr><th>");
				html.append(key);
				html.append("</th><td>");
				html.append(request.getHeader(key));
				html.append("</td></tr>");
			}
			html.append("</table><h2>Request Parameters</h2><table>");
			Enumeration params = request.getParameterNames();
			while (params.hasMoreElements()) {
				String key = (String) params.nextElement();
				html.append("<tr><th>");
				html.append(key);
				html.append("</th><td>");
				html.append(request.getParameter(key));
				html.append("</td></tr>");
			}
			html.append("</table>");
		}
		html.append("<h2>");
		html.append(t.getClass().getName());
		html.append('(');
		html.append(DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
		html.append(")</h2><pre>");
		try {
			html.append(HtmlHelper.changeHtmlMark(exception(t)));
		} catch (IOException ex) {
		}
		html.append("</pre>");
		html.append("<h2>System Properties</h2><table>");
		Set props = System.getProperties().keySet();
		for (Object prop : props) {
			html.append("<tr><th>");
			html.append(prop);
			html.append("</th><td>");
			html.append(System.getProperty((String) prop));
			html.append("</td></tr>");
		}
		html.append("</table>");
		return html.toString();
	}
	
	/**
	 * 将异常信息转化成字符串
	 * @param t
	 * @return
	 * @throws IOException
	 */
	private static String exception(Throwable t) throws IOException{
	    if(t == null)
	        return null;
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    try{
	        t.printStackTrace(new PrintStream(baos));
	    }finally{
	        baos.close();
	    }
	    return baos.toString();
	}
}
